import Vue from 'vue';
import VueRouter from 'vue-router';
import {routers, otherRouters, appRouters,flowInstanceRouters,flowSchemeRouters,formSchemeRouters} from './router';
import iView from 'view-design';

import Util from '@/lib/util';
import Cookies from 'js-cookie';

Vue.use(VueRouter);

const router = new VueRouter({
    routes: routers,
});

export default router;

router.beforeEach((to, from, next) => {
    (iView as any).LoadingBar.start();
    Util.title(to.meta.title);
    if (Cookies.get('locking') === '1' && to.name !== 'locking') {
        next({
            replace: true,
            name: 'locking',
        });
    } else if (Cookies.get('locking') === '0' && to.name === 'locking') {
        next(false);
    } else {
        if (!Util.abp.session.userId && to.name !== 'login') {
            next({
                name: 'login',
            });
        } else if (!!Util.abp.session.userId && to.name === 'login') {
            Util.title(to.meta.title);
            next({
                name: 'home',
            });
        } else {
            const curRouterObj = Util.getRouterObjByName([otherRouters, ...appRouters,flowInstanceRouters,flowSchemeRouters,formSchemeRouters], to.name);
            if (curRouterObj && curRouterObj.permission) {
                if (window.abp.auth.hasPermission(curRouterObj.permission)) {
                    Util.toDefaultPage([otherRouters, ...appRouters,flowInstanceRouters,flowSchemeRouters,formSchemeRouters], to.name, router, next);
                } else {
                    next({
                        replace: true,
                        name: 'error-403',
                    });
                }
            } else {
                Util.toDefaultPage([...routers], to.name, router, next);
            }
        }
    }

    next();
});

router.afterEach((to) => {
    Util.openNewPage(router.app, to.name, to.params, to.query);
    (iView as any).LoadingBar.finish();
    window.scroll(0, 0);
});
